package com.edu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.user.domain.dto.NotificationDTO;
import com.edu.user.domain.po.Notification;
import com.edu.user.mapper.NotificationMapper;
import com.edu.user.service.NotificationService;
import com.edu.user.websocket.WebSocket;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class NotificationServiceImpl extends ServiceImpl<NotificationMapper, Notification> implements NotificationService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public void sendNotification(NotificationDTO notificationDTO) {
        Notification notification = new Notification();
        notification.setUserId(notificationDTO.getUserId());
        notification.setMessage(notificationDTO.getMessage());
        // 创建格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.now();
        // 格式化 LocalDateTime 对象
        String formattedDateTime = localDateTime.format(formatter);
        notification.setSendTime(formattedDateTime);
        notification.setStatus("未读"); // 设置初始状态为未读
        this.save(notification);
        // 检查用户是否在线并发送 WebSocket 消息
      //  WebSocket.sendMessageToUser(notificationDTO.getUserId(), "您有一条新消息");
    }
    @Override
    public List<Notification> getNotificationsByUserId(Long userId) {
        QueryWrapper<Notification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        //将通知状态改成已读
        List<Notification> list = list(queryWrapper);
        for (Notification notification : list) {
            markAsRead(notification.getId());
        }
        return list;
    }

    @Override
    public void markAsRead(Long notificationId) {
        Notification notification = getById(notificationId);
        if (notification != null && "未读".equals(notification.getStatus())) {
            notification.setStatus("已读");
            updateById(notification);
        }
    }
}
